#!/usr/bin/perl 
#mdm_nfs.cgi

require "./mdmjobs-lib.pl";
&ReadParse(); 
&foreign_require("protocolman","protocolman-lib.pl");

&header($text{'res_NFS_detail'}, "", "index", 0, 1);

&remote_error_setup(\&inst_error);
$| = 1;

local @in_members=split(/,/,$in{'listinput'});
local $grpinfo=&foreign_call("mdmgroups","get_groupinfo");
local %grpinfo=%$grpinfo;
local @group = split (/,/,$grpinfo{'[group]'});
local $own_upgrade=0;
local @devices;
foreach(@in_members){
	if (/\[This server\]/){
		$own_upgrade=1;
		next;
	}elsif (/^@/){
		local $grpname=$_;
		$grpname=~ s/@//;
		local $devs=$grpinfo{"$grpname"};
		local @devs=split(/,/,$devs);
		foreach $s (@devs){
			if ($s=~/\[This server\]/){
				$own_upgrade=1;
				next;
			}						
			push (@devices,$s);
		}
	}elsif(/^\[/){
		push (@devices,$_);
	}	
}

local %single;
local @servers;
foreach $serv (@devices){
	if (!$single->{"$serv"}++){
		push @servers,$serv;
	}
}

@devices = sort { $a cmp $b } @servers;
$p=0;
foreach $s (@devices){
	local ($rh = "READ$p", $wh = "WRITE$p");
	pipe($rh, $wh);
	select($wh); $| = 1; select(STDOUT);
	
	local $hostid = $s;
	$hostid =~ s/\[//;
	$hostid =~ s/\].*//;
	if (!fork()) {
		close($rh);
		local $rst;
		local @rst;
		&remote_foreign_require($hostid, "protocolman","protocolman-lib.pl");	
		if ($in{'setnfs'} eq 'start'){
			$rst = &remote_foreign_call($hostid, "protocolman", "mdm_startnfs");
			push(@rst,$rst);
		}elsif ($in{'setnfs'} eq 'stop'){
			$rst = &remote_foreign_call($hostid, "protocolman", "mdm_stopnfs");
			push(@rst,$rst);			
		}elsif ($in{'setnfs'} eq 'restart'){
			$rst = &remote_foreign_call($hostid, "protocolman", "mdm_restartnfs");
			push(@rst,$rst);			
		}
		print $wh &serialise_variable(\@rst);
		close($wh);
		exit;
	}
	
	close ($wh);
	$p++;	
}

local @data;
local $logoper;
if ($in{'setnfs'} eq 'start'){
	$logoper="Start NFS";	
}elsif ($in{'setnfs'} eq 'stop'){
	$logoper="Stop NFS";
}elsif ($in{'setnfs'} eq 'restart'){
	$logoper="Restart NFS";
}

if($own_upgrade == 1){
	local $rst;
	if ($in{'setnfs'} eq 'start'){
		$rst= &foreign_call("protocolman","mdm_startnfs");
	}elsif ($in{'setnfs'} eq 'stop'){
		$rst= &foreign_call("protocolman","mdm_stopnfs");
	}elsif ($in{'setnfs'} eq 'restart'){
		$rst= &foreign_call("protocolman","mdm_restartnfs");
	}

	push @data,"This Server return is: $rst";
	print "<p>This Server return is: $rst\n";
}

$p = 0;
foreach $s (@devices) {
	local $rh = "READ$p";
	local $line = <$rh>;
	close($rh);
	
	local $rv = &unserialise_variable($line);
	@rv=@$rv;
	if (! @rv){
		push @data,"$s return is: $text{'noanswer'}";
		print "<p>$s return is: $text{'noanswer'}";
	}else{
		local $line=join("; ",@rv);
		push @data,"$s return is: $line";
		print "<p>$s return is: $line\n";
	}
	
	$p++;	
}

&foreign_call("mdmhistory","mdm_log",$logoper,\@data);	

&remote_finished();	
&footer("./index.cgi", $text{'index_title'});			